package prototyping;

import java.rmi.RMISecurityManager;

import net.jini.core.lookup.ServiceItem;
import net.jini.core.lookup.ServiceTemplate;
import net.jini.discovery.LookupDiscoveryManager;
import net.jini.lease.LeaseRenewalManager;
import net.jini.lookup.ServiceDiscoveryManager;
import net.jini.space.JavaSpace;

public class SpaceTest {
	
	public static void main(String[] args) {
		
		// Install security manager
		System.setProperty("java.security.policy", "test.policy");
		System.setSecurityManager(new RMISecurityManager());
	
		try {
			
			
			//java.sql.Date currentTimestamp = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime());
		
			// Get lookup service
			LookupDiscoveryManager discoveryMgr = new LookupDiscoveryManager(new String [] {"JORSEBREGGIE"}, null, null);
			ServiceDiscoveryManager serviceMgr = new ServiceDiscoveryManager(discoveryMgr, new LeaseRenewalManager());
	
			// Search for MarketeteerClient service
			Class[] classes = new Class[] { JavaSpace.class }; 
			ServiceTemplate template = new ServiceTemplate(null, classes, null);
			ServiceItem item = null;
			item = serviceMgr.lookup(template, null, 1000L);
	
			// Get the service
			if (item == null) {
				System.out.println("JavaSpace1 not found"); 
				System.exit(1);
			}
			JavaSpace space = (JavaSpace) item.service;
			if (space == null) { 
				System.out.println("JavaSpace2 not found"); 
				System.exit(1);
			}
			
			System.out.println("Space found");
			
			SpaceItem msg = new SpaceItem("Hello there");
			System.out.println("Writing a message into the space...");
			space.write(msg, null, 60 * 60 * 1000);
			SpaceItem template2 = new SpaceItem();
			System.out.println("Reading a message from the space...");
			SpaceItem result = (SpaceItem) space.read(template2, null,
					Long.MAX_VALUE);
			System.out.println("The message read is: " + result.content);
		
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
